package kr.ac.kaist.simplefileexplorer.connection;

import java.util.ArrayList;

import kr.ac.kaist.simplefileexplorer.SeeMyFileActivity;
import kr.ac.kaist.simplefileexplorer.connection.push.GooglePushClient;
import kr.ac.kaist.simplefileexplorer.entity.ShareRequestEntity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

class HttpTask extends AsyncTask<Object , Void , Object> {
	
	final static String ContactCloudClient_TAG = "ContactCloudClient";
	
	  protected Object doInBackground(Object... params)
	  {
		ShareRequestEntity entity = (ShareRequestEntity) params[0];
		  
	    String uuid = ContactCloudClient.shareFiles(entity.getMyContact(), entity.getCloudFileUrl(), entity.getTitleOfFile(), entity.getContacts(), entity.getDueDate(), entity.getDownloadLimit());
		Log.i(ContactCloudClient_TAG, "uuid: " +  uuid);
		
		entity.setUUID(uuid);
		
	    return entity;
	  }

	  // Called by main thread.
	  protected void onPostExecute(Object result)
	  {
			ShareRequestEntity entity = (ShareRequestEntity) result;		  
		  
			Log.i(ContactCloudClient_TAG, "onPostExecute: " + entity.getUUID());
			
			GooglePushClient.pushMessageByAsync(entity.getUUID(), entity.getMyContact(), entity.getContacts());
			
			entity.makeToast();
			
	  }
} 	

public class ContactCloudClient {
	
	final static String ContactCloudClient_TAG = "ContactCloudClient";

	final static String HTTP_SERVER_URL = "http://141.223.191.155:5132/";

	final static String HTTPS_SERVER_URL = "https://141.223.191.155:5023/";

	final static String CREATE_URI = "create";

	final static String READ_URI = "read";

	final static int HTTP_CONNECTION_TIMEOUT = 30 * 1000;		
	
	public static String shareFilesByAsync(String myContact, String cloudFileUrl,
			String titleOfFile, String contacts, String dueDate,
			String downloadLimit, SeeMyFileActivity activity) {
				
		String result = "progress";
		
		ShareRequestEntity entity = new ShareRequestEntity(myContact, cloudFileUrl, titleOfFile, contacts, dueDate, downloadLimit, activity);
		
		new HttpTask().execute(entity); 	
		
		return result;				
	}
		
	/**
	 * - json:
	 * '{"myContact":"01192873938","cloudFileUrl":"www.dropbox.com/aA94fjke234","Filename":"Description
	 * " , "contacts":"0109982738;01093947476;","dueDate":"2014-02-01",
	 * "downloadLimit":"99"}' - result: uuid value(plain text)
	 * 
	 * @return
	 */
	public static String shareFiles(String myContact, String cloudFileUrl,
			String titleOfFile, String contacts, String dueDate,
			String downloadLimit) {
		HttpClient client;
		HttpPost post;
		client = new DefaultHttpClient();
		String uuid = null;

		Log.i(ContactCloudClient_TAG, "myContact: " + myContact + " cloudFileUrl: "+ cloudFileUrl + " Filename: " + titleOfFile + " contacts: " + contacts + " dueDate: " + dueDate + " downloadLimit: " + downloadLimit);
		
		HttpConnectionParams.setConnectionTimeout(client.getParams(),
				HTTP_CONNECTION_TIMEOUT);
		post = new HttpPost(HTTP_SERVER_URL + CREATE_URI);

		try {
			JSONObject jsonObject = new JSONObject();

			jsonObject.put("myContact", myContact);			
			jsonObject.put("cloudFileUrl", cloudFileUrl);
			jsonObject.put("Filename", titleOfFile);
			jsonObject.put("contacts", contacts);
			jsonObject.put("dueDate", dueDate);
			jsonObject.put("downloadLimit", downloadLimit);
			
			String removedUrl = jsonObject.toString().replace("\\", "");
			Log.i(ContactCloudClient_TAG, "json value: " + removedUrl);
			
			StringEntity jsonEntity = new StringEntity(removedUrl,
					HTTP.UTF_8);			
			
			jsonEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			post.setEntity(jsonEntity);

			HttpResponse response = client.execute(post);
			HttpEntity responseEntity = response.getEntity();
			uuid = EntityUtils.toString(responseEntity);
			
			Log.i(ContactCloudClient_TAG, "==> uuid: " + uuid);			

		} catch (Exception e) {
			e.printStackTrace();
		}

		return uuid;
	}
	
	
	public static ArrayList<ShareRequestEntity> getSharedFile(String myContact) {
		HttpClient client;
		HttpPost post;
		client = new DefaultHttpClient();
		String jsonResultString = null;

		Log.i(ContactCloudClient_TAG, "myContact: " + myContact);
		
		HttpConnectionParams.setConnectionTimeout(client.getParams(),
				HTTP_CONNECTION_TIMEOUT);
		post = new HttpPost(HTTP_SERVER_URL + READ_URI);
		
		ArrayList<ShareRequestEntity> resultList = new ArrayList<ShareRequestEntity>();

		try {
			JSONObject jsonObject = new JSONObject();

			jsonObject.put("contact", myContact);			
			
			String jsonString = jsonObject.toString();
			Log.i(ContactCloudClient_TAG, "json value: " + jsonString);
			
			StringEntity jsonEntity = new StringEntity(jsonString,
					HTTP.UTF_8);			
			
			jsonEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			post.setEntity(jsonEntity);

			HttpResponse response = client.execute(post);
			HttpEntity responseEntity = response.getEntity();
			jsonResultString = EntityUtils.toString(responseEntity);
			Log.i(ContactCloudClient_TAG, "==> jsonResultString: " + jsonResultString);		
			
			JSONObject jsonResponse = new JSONObject(jsonResultString);
			JSONArray array = jsonResponse.getJSONArray("result");		
			
			Log.i(ContactCloudClient_TAG, "length: " + array.length());
			
			for (int i = 0; i < array.length(); i++) {
				
				JSONObject element = array.optJSONObject(i);
				if (element == null)
					continue;
				String myPhoneNumber = element.getString("myContact");
				String cloudFileUrl = element.getString("cloudFileUrl");
				String fileName = element.getString("Filename");
				String contacts = element.getString("contacts");
				String dueDate = element.getString("dueDate");
				String downloadLimit = element.getString("downloadLimit");				
				Log.i(ContactCloudClient_TAG, "[" + i + "]" + "myContact: " + myPhoneNumber + " cloudFileUrl: "+ cloudFileUrl + " Filename: " + fileName + " contacts: " + contacts + " dueDate: " + dueDate + " downloadLimit: " + downloadLimit);
			
				ShareRequestEntity entity = new ShareRequestEntity(myPhoneNumber, cloudFileUrl, fileName, contacts, dueDate, downloadLimit);
				resultList.add(entity);			
			}	

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultList;
	}
	
	
}
